<!DOCTYPE html>
<html>
  <head>
    <title>Canvas Translate Rectangle</title>
  </head>
  <body>
    <canvas
      id="myCanvas"
      width="400"
      height="400"
      style="border: 1px solid #000000"
    ></canvas>
    <button id="moveButton">move image</button>
    <button id="scaleButton">scale image</button>
    <button id="rotateButton">rotate image</button>

    <script>
      var canvas = document.getElementById("myCanvas");
      var ctx = canvas.getContext("2d");
      var image = new Image();
      let params = {
        x: 50,
        y: 50,
        width: 100,
        height: 100,
        scale: 1,
        rotate: 0,
        translateX: 0,
        translateY: 0,
      }
      image.src = "https://www.runoob.com/try/demo_source/paris.jpg";
      
      function drawImage() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.save();
        ctx.translate(params.translateX, params.translateY);
        ctx.scale(params.scale, params.scale);
        ctx.rotate(params.rotate * Math.PI / 180);
        ctx.drawImage(image, params.x, params.y, params.width, params.height);
        ctx.restore();
      }

      image.onload = function () {
        drawImage();
      };

      document.getElementById("moveButton").addEventListener("click", function () {
        console.log('moveButton')
        params.translateX += 10;
        params.translateY += 10;
        if (params.translateX > 400 || params.translateY > 400) {
          params.translateX = 0;
          params.translateY = 0;
        }
        drawImage();
      });

      /**
       * 缩放和旋转 此处省略，看前边的代码
      */
    </script>
  </body>
</html>
